package cn.iocoder.yudao.module.infra.code;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author
 */
//@Component
public class AutoCodeUtils{

    private static final Log logger = LogFactory.getLog(AutoCodeUtils.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     *  redis的key
     * @param key
     * @param code
     * @return
     */
    public String autoCode(String key, StringBuilder code){
        try {
            String redisValue = stringRedisTemplate.opsForValue().get(key);
            //判断key是否存在
            if (StringUtils.isNotEmpty(redisValue)){
                //以增量的方式（默认增量为1）将long值存储在变量中(value为其他类型时报错)，返回最新值
                Long incrKey = stringRedisTemplate.opsForValue().increment(key);
                if (incrKey > SequenceRuleConstant.RANDOM_MIN_VALUE) {
                    String info = (incrKey + "");
                    code.append(info.substring(info.length() - SequenceRuleConstant.REDIS_DEFAULT_DIGIT));
                } else {
                    String result = String.format(SequenceRuleConstant.REDIS_DEFAULT_DIGIT_FORMAT, incrKey);
                    code.append(result);
                }

            } else {
                stringRedisTemplate.boundValueOps(key).set("1",1, TimeUnit.DAYS);
                code.append(String.format(SequenceRuleConstant.REDIS_DEFAULT_DIGIT_FORMAT, 1));
            }
        } catch (Exception e) {
            logger.error("redis database error,please check your config", e);
            //异常时 生成默认四位随机数
            code.append(random(SequenceRuleConstant.APP_DEFAULT_DIGIT));
        }
        return code.toString();
    }


    /**
     * 随机
     *
     * @param length
     * @return
     */
    public String random(int length) {
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            result.append(random.nextInt(10));
        }
        return result.toString();
    }

    public StringBuilder timeCode(){
        LocalDate date = LocalDate.now();
        String year = String.valueOf(date.getYear());
        String month = String.format(SequenceRuleConstant.BIZ_DEFAULT_DIGIT_FORMAT, date.getMonthValue());
        String day = String.format(SequenceRuleConstant.BIZ_DEFAULT_DIGIT_FORMAT, date.getDayOfMonth());
        LocalTime time = LocalTime.now();
        String hour = String.format(SequenceRuleConstant.BIZ_DEFAULT_DIGIT_FORMAT, time.getHour());
        String minute = String.format(SequenceRuleConstant.BIZ_DEFAULT_DIGIT_FORMAT, time.getMinute());
        String second = String.format(SequenceRuleConstant.BIZ_DEFAULT_DIGIT_FORMAT, time.getSecond());
        StringBuilder code = new StringBuilder();
        //年 + 月 + 日 + 时分秒 +当日自增序列
        code.append(year).append(month).append(day).append(hour).append(minute).append(second);
        return code;
    }
}
